package com.example.filecollectionsystemdemo1.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.filecollectionsystemdemo1.common.AuthAccess;
import com.example.filecollectionsystemdemo1.common.Result;
import com.example.filecollectionsystemdemo1.entity.Files;
import com.example.filecollectionsystemdemo1.service.FilesService;
import com.example.filecollectionsystemdemo1.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 功能：
 * 作者：lanbingyue1
 * 日期：2023/12/8 12:30
 */
@CrossOrigin
@RestController
@RequestMapping("/files")
public class FilesController {
    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    @Autowired
    private FilesService filesService;

    @Autowired
    private UsersService usersService;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam("folderid") Integer folderid) throws IOException {
        //// 从请求头中获取JWT
        //String token = request.getHeader("token");
        //
        //Integer uploaderid;
        //try {
        //    String userId = JWT.decode(token).getAudience().get(0);
        //    uploaderid = Integer.parseInt(userId);
        //} catch (JWTDecodeException e) {
        //    return Result.error("未登录或用户ID未设置");
        //}
        // 从当前用户中获取用户ID
        Integer uploaderid;
        uploaderid = usersService.getCurrentUser().getUserid();

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 文件名（不含扩展名）
        String mainName = FileUtil.mainName(originalFilename);
        // 文件扩展名
        String extName = FileUtil.extName(originalFilename);

        // 如果父目录不存在，则创建
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);
        }
        // 如果文件已存在，则重命名
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }

        // 保存文件
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);

        // 保存文件信息到数据库
        Files fileInfo = new Files();
        fileInfo.setFilename(originalFilename);
        fileInfo.setFilesize((int) file.getSize());
        fileInfo.setFilepath(saveFile.getAbsolutePath());
        fileInfo.setUploaddate(new Date());


        //TODO：前端传入文件夹ID


        fileInfo.setUploaderid(uploaderid);
        fileInfo.setFolderid(folderid);

        // 保存文件信息到数据库
        filesService.save(fileInfo);

        // 构造文件下载URL
        String url = "http://" + ip + ":" + port + "/files/download/" + originalFilename;
        return Result.success(url);
    }


    @AuthAccess
    @GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId, HttpServletResponse response) throws IOException {
        // 假设你有一个方法来根据ID获取文件名
        String fileName = filesService.getById(fileId).getFilename();
        if (fileName == null) {
            // 如果找不到文件名，返回404或其他错误响应
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)) {
            // 如果文件不存在，返回404或其他错误响应
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    //核心
    //批量下载
    //@PostMapping("/download/batch")
    //public void downloadBatch(@RequestBody List<String> fileIds, HttpServletResponse response) throws IOException {
    //    // 根据fileIds获取文件并创建ZIP文件
    //    File zipFile = createZipFileFromIds(fileIds);
    //    response.setContentType("application/zip");
    //    response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("files.zip", "UTF-8"));
    //
    //    try (FileInputStream fis = new FileInputStream(zipFile);
    //         OutputStream os = response.getOutputStream()) {
    //        byte[] buffer = new byte[1024];
    //        int bytesRead;
    //        while ((bytesRead = fis.read(buffer)) != -1) {
    //            os.write(buffer, 0, bytesRead);
    //        }
    //        os.flush();
    //    }
    //}



    //编辑器上传文件
    //@PostMapping("/editor/upload")
    //public Dict editorUpload(@RequestParam MultipartFile file, @RequestParam String type) throws IOException {
    //    String originalFilename = file.getOriginalFilename();
    //    String mainName = FileUtil.mainName(originalFilename);
    //    String extName = FileUtil.extName(originalFilename);
    //    if (!FileUtil.exist(ROOT_PATH)) {
    //        FileUtil.mkdir(ROOT_PATH);
    //    }
    //    if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
    //        originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
    //    }
    //    File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
    //    file.transferTo(saveFile);
    //
    //    Files fileInfo = new Files();
    //    fileInfo.setFilename(originalFilename);
    //    fileInfo.setFilesize((int) file.getSize());
    //    fileInfo.setFilepath(saveFile.getAbsolutePath());
    //    fileInfo.setUploaddate(new Date());
    //    // Assume the uploaderid and folderid are set somewhere
    //    Integer uploaderid = 1; // Example uploader ID
    //    Integer folderid = 1; // Example folder ID
    //    fileInfo.setUploaderid(uploaderid);
    //    fileInfo.setFolderid(folderid);
    //    filesService.save(fileInfo);
    //
    //    String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
    //    Dict data = Dict.create().set("url", url);
    //
    //    List<String> imageTypes = Arrays.asList("jpg", "png", "gif", "bmp", "jpeg");
    //    List<String> documentTypes = Arrays.asList("doc", "docx", "ppt", "pptx");
    //    List<String> archiveTypes = Arrays.asList("zip", "rar");
    //
    //    if (imageTypes.contains(extName)) {
    //        return Dict.create().set("errno", 0).set("data", CollUtil.newArrayList(data));
    //    } else if (documentTypes.contains(extName)) {
    //        return Dict.create().set("errno", 0).set("data", data.set("document", "This is a document"));
    //    } else if (archiveTypes.contains(extName)) {
    //        return Dict.create().set("errno", 0).set("data", data.set("archive", "This is an archive"));
    //    } else {
    //        return Dict.create().set("errno", 0).set("data", data);
    //    }
    //}
    //删除文件
    @DeleteMapping("/delete/{fileId}")
    public Result delete(@PathVariable Integer fileId) {
        Files files = filesService.getById(fileId);
        if (files == null) {
            return Result.error("文件不存在");
        }
        File file = new File(files.getFilepath());
        if (file.exists()) {
            file.delete();
        }
        filesService.removeById(fileId);
        return Result.success();
    }
    //批量删除文件
    @AuthAccess
    @PostMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {

        filesService.removeBatchByIds(ids);
        return Result.success();
    }

    //模糊查询文件信息
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String filename) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>().orderByDesc("FileID");
        queryWrapper.like(StrUtil.isNotBlank(filename), "Filename", filename);
        Page<Files> page = filesService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    //模糊查询文件信息
    @GetMapping("/selectByPageByFolderId")
    public Result selectByPageByFolderId(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String folderId) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>().orderByDesc("FileID");
        queryWrapper.like(StrUtil.isNotBlank(folderId), "FolderID", folderId);
        Page<Files> page = filesService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    //selectAll
    @AuthAccess
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Files> filesList = filesService.list(new QueryWrapper<Files>().orderByDesc("FileID"));
        return Result.success(filesList);
    }
    //展示相同文件夹id的文件
    @GetMapping("/selectByFolderId/{folderId}")
    public Result selectByFolderId(@PathVariable Integer folderId) {
        if (folderId == null) {
            return Result.error("文件夹 ID 是必需的");
        }
        List<Files> filesList = filesService.list(new QueryWrapper<Files>().eq("FolderID", folderId).orderByDesc("FileID"));
        return Result.success(filesList);
    }

}